package com.xxxx.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.seckill.mapper.UserMapper;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.pojo.dto.LoginDto;
import com.xxxx.seckill.service.IUserService;
import com.xxxx.seckill.utils.CookieUtil;
import com.xxxx.seckill.utils.MD5Util;
import com.xxxx.seckill.utils.UUIDUtil;
import com.xxxx.seckill.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2022-08-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean login(LoginDto loginDto, HttpServletRequest request, HttpServletResponse resp) {
        log.info("登陆方法。。。。。。");
        //查询数据库判断是否存在该用户
        User user = this.getById(loginDto.getMobile());
        if (user == null) {
            return RespBean.error("用户不存在");
        }
        String pass = MD5Util.inputPassToDbPass(loginDto.getPassword(), "1a2b3c4d");
        if (!user.getPassword().equals(pass)) {
            log.info("flag:{}", !user.getPassword().equals(pass));
            return RespBean.error("密码错误");
        }

//        查看用户是否已经登录，若已经登陆，则不需要生成cookie
        String cookie = CookieUtil.getCookieValue(request, "user");
        if (cookie != null) {
            String json = (String) redisTemplate.opsForValue().get("user:" + cookie);
            if (!StringUtils.isEmpty(json)) {
                //存入缓存,缓存时间 3h
                String newid = CookieUtil.getCookieValue(request, "user");
                redisTemplate.opsForValue().set("user:" + newid, JSON.toJSONString(user), 60 * 60 * 3, TimeUnit.SECONDS);
                return RespBean.success();
            }
        }
//        用户未登陆过，存cookie
        String uuid = UUIDUtil.uuid();
        CookieUtil.setCookie(request, resp, "user", uuid);
        //存入缓存,缓存时间 3h
        redisTemplate.opsForValue().set("user:" + uuid, JSON.toJSONString(user), 60 * 60 * 3, TimeUnit.SECONDS);
        log.info("登陆成功。。。。。。。");
        return RespBean.success(uuid);
    }
}